import { _decorator, Component, Node } from "cc";
const { ccclass, property } = _decorator;
// let URL = "http://101.35.8.219:9000";
let URL = "http://127.0.0.1:9000";
export interface RequestType {
  [key: string]: any;
  setURL: (a: string) => any;
  sendRequest: (
    url: string,
    data: any,
    handler: any,
    extraUrl?: any
  ) => XMLHttpRequest;
}
export const config = {
  master_url: "",
  url: URL,
  token: "",
};
export function setURL(url) {
  config.url = url;
}

interface XML extends XMLHttpRequest {
  hasRetried?: boolean;
}
export function sendRequest(path, data, handler, extraUrl): XML {
  // cc.assetManager.
  // cc.
  // cc.assetManager.
  var xhr: XML = new XMLHttpRequest();
  xhr.timeout = 5000;

  if (data == null) {
    data = {};
  }
  if (config.token) {
    data.token = config.token;
  }

  if (!extraUrl) {
    extraUrl = config.url;
  }

  //解析请求路由以及格式化请求参数
  var sendpath = path;
  var sendtext = "?";
  for (var k in data) {
    if (sendtext != "?") {
      sendtext += "&";
    }
    sendtext += k + "=" + data[k];
  }

  //组装完整的URL
  var requestURL = extraUrl + sendpath + encodeURI(sendtext);

  //发送请求
  console.log("RequestURL:" + requestURL);
  xhr.open("GET", requestURL, true);

  if (cc.sys.isNative) {
    // xhr.setRequestHeader("Accept-Encoding", "gzip,deflate", "text/html;charset=UTF-8");
    xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
  }

  var timer = setTimeout(function () {
    xhr.hasRetried = true;
    xhr.abort();
    retryFunc();
  }, 5000);

  var retryFunc = function () {
    sendRequest(path, data, handler, extraUrl);
  };

  xhr.onreadystatechange = function () {
    clearTimeout(timer);
    if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
      // console.log("http res(" + xhr.responseText.length + "):" + xhr.responseText);
      let respText = xhr.responseText;

      let ret = null;
      try {
        ret = JSON.parse(respText);
      } catch (e) {
        ret = {
          errcode: -10001,
          errmsg: e,
        };
      }
      cc.log("request from [" + xhr.responseURL + "] data [", ret, "]");

      if (handler) {
        handler(ret);
      }

      handler = null;
    } else if (xhr.readyState === 4) {
      if (xhr.hasRetried) {
        return;
      }

      console.log("other readystate == 4" + ", status:" + xhr.status);
      setTimeout(function () {
        retryFunc();
      }, 5000);
    } else {
      console.log(
        "other readystate:" + xhr.readyState + ", status:" + xhr.status
      );
    }
  };

  try {
    xhr.send();
  } catch (e) {
    //setTimeout(retryFunc, 200);
    retryFunc();
  }

  return xhr;
}
